sudo apt install protoc-gen-go
go env -w CGO_ENABLED=0
go env -w GOOS=linux
go env -w GOARCH=amd64

function install() {

    go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
    go install github.com/favadi/protoc-go-inject-tag@latest
    go install \
       github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \
       github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
}
#install

export PATH=$PATH:/home/debi/go/bin

base_dir=$(
  cd "$(dirname "$0")"
  pwd
)
function logger() {
      front=$1
      back=$2
      content=$3
      echo -e "\e["$back";"$front"m"$content"\e[0m"
}
cd $base_dogger 33 40 "Current $base_dir"

function ParseTogether() {
    protoPath=$1
    outDir=$2
    extraDirMap=$(declare -p "$3")
    declare -A targetMap=${extraDirMap#*=}
    logger 34 40 "your extraDir: targetMap"
    for absPath in $base_dir/$protoPath/* ; do
        echo $absPath
        if [[ $absPath == *".proto" ]]; then
            fileName=$(basename $absPath)
            fileNameNoExt=$(echo $fileName | cut -d . -f1)
            fileDir=$(dirname $absPath )
            goOutDir=$base_dir/$outDir/ # dir/*.pd.go
            mkdir -p $goOutDir
             for key in ${!targetMap[*]};do
                    value=${targetMap[$key]}
                    goOutExtraDir=$base_dir/"$outDir"/"$value"
                    mkdir -p $goOutExtraDir
                    if [ ! -f "$goOutExtraDir"/$fileNameNoExt."$key".go ]; then
                              echo "package "$value"" > $goOutExtraDir/"$fileNameNoExt"."$key".go
                              logger 36 40 "$goOutExtraDir/"$fileNameNoExt"."$key".go create!"
                    fi
             done
              logger 36 40 $absPath
              protoc -I ../.  -I=.  -I=./..  \
                             --proto_path=$base_dir/$protoPath  \
                             --go_out $goOutDir --go_opt paths=source_relative \
                             --go-grpc_out $goOutDir --go-grpc_opt paths=source_relative \
                             --grpc-gateway_out $goOutDir  --grpc-gateway_opt paths=source_relative \
                             --grpc-gateway_opt logtostderr=true \
                            $fileName
                protoc-go-inject-tag -input $goOutDir/"*.pb.go"
        fi
    done
}

#proto相对路径 输出相对路径 要创建的文件夹
declare -A def=( )
ParseTogether "api" "test" def
